import * as WebSocket from 'ws';
import { DBManager } from './manager/DBManager';

export class Socket
{
    //会有多个连接
    private sessions:Array<WebSocket>;
    private _wss: WebSocket.Server;
    constructor()
    {
        this.sessions = new Array<WebSocket>();
    }

    /**初始化websocket */
    public init(port:number): void
    {
        this._wss = new WebSocket.Server({ port: port });
        
        console.log('websocket linsten on:',port);
        let self = this;
        this._wss.on('connection', function connection(ws,req)
        {
            console.log('url:',req.url);//解析url
            self.sessions.push(ws);
            ws.on('message', function incoming(message)
            {
                // console.log('received: %s', message);
                DBManager.getInstance().messageParse(ws,message);
            });
            // ws.send('something');
        });
    }
}